package com.example.droplistitems;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.ArrayRes;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;

public class DropList extends AppCompatActivity {

    Spinner spinner;
    Spinner spinner2;

    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drop_list);

        spinner = (Spinner) findViewById(R.id.spinner);
        spinner2 = (Spinner) findViewById(R.id.spinner2);


        //region 利用entries属性配置字符串数据文件，无适配器

        /**
         * 配置选择监听事件
         */
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String result = parent.getItemAtPosition(position).toString();
                Toast.makeText(DropList.this, getStrResource(R.string.tip1) + " " + result, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //endregion

        //region 使用适配器定制化各种下拉样式，灵活配置字符文件
        adapter = new ArrayAdapter<String>(DropList.this, R.layout.spinner_items, R.id.textView1, getStrArrayResource(R.array.dtype));
        adapter.setDropDownViewResource(R.layout.spinner_items);
        spinner2.setAdapter(adapter);
        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String result = spinner2.getSelectedItem().toString();
                Toast.makeText(DropList.this, getStrResource(R.string.tip1) + " " + result, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //endregion


    }

    public String getStrResource(@StringRes int id) {
        return getResources().getString(id);
    }

    public String[] getStrArrayResource(@ArrayRes int id) {
        return getResources().getStringArray(id);
    }

}